package cn.hzc.fortess.config;


import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.MimeType;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Configuration
@ConditionalOnClass({MimeMessage.class, MimeType.class})
@ConditionalOnMissingBean(MailSender.class)
@EnableConfigurationProperties(MailProperties.class)
public class MailSenderConfiguration {

    private final MailProperties properties;
    private final Session session;


    public MailSenderConfiguration(MailProperties properties,
                                   ObjectProvider<Session> session) {
        this.properties = properties;
        this.session = session.getIfAvailable();
    }


    @Bean
    public JavaMailSender mailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        if (this.session != null) {
            sender.setSession(this.session);
        } else {
            applyProperties(sender);
        }
        return sender;
    }

    private void applyProperties(JavaMailSenderImpl sender) {
        sender.setHost(properties.getHost());
        if (properties.getPort() != null) {
            sender.setPort(properties.getPort());
        }
        sender.setPassword(properties.getPassword());
        sender.setProtocol(properties.getProtocol());
        sender.setUsername(properties.getUsername());
        sender.setDefaultEncoding("UTF-8");



    }
}
